const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

// 解决跨域问题
const cors = require('cors')

// 导入路由文件

// 后台管理系统路由文件
const AdminUserApiRouter = require('./routes/apis/auth')  //管理员登录
const AdminPropertyApiRouter = require('./routes/apis/property')  //后台管理系统房源路由
const AdminOrderApiRouter = require('./routes/apis/order')  //后台管理系统预约记录路由
const AdminEvaluateApiRouter = require('./routes/apis/evaluate')  //后台管理系统评价记录路由
const AdminInfoApiRouter = require('./routes/apis/admin') //后台管理系统管理员信息路由
const AdminChartApiRouter = require('./routes/apis/chart')  //后台管理系统图表路由

// 前端网站路由文件
const UserApiRouter = require('./routes/web/auth')  //用户登录
const CarouselApiRouter = require('./routes/web/carousel')  //轮播图路由
const PropertyApiRouter = require('./routes/web/property')  //房源路由
const OrderApiRouter = require('./routes/web/order')  //用户预约看房路由
const UserInfoApiRouter = require('./routes/web/user')  //用户个人信息路由
const EvaluateApiRouter = require('./routes/web/evaluate')  //用户评价信息路由

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 解决跨域问题
app.use(cors())

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 使用路由

// 后台管理系统
app.use('/api', AdminUserApiRouter)
app.use('/api', AdminPropertyApiRouter)
app.use('/api', AdminOrderApiRouter)
app.use('/api', AdminEvaluateApiRouter)
app.use('/api', AdminInfoApiRouter)
app.use('/api', AdminChartApiRouter)


// 前端网站
app.use('/', UserApiRouter)
app.use('/', CarouselApiRouter)
app.use('/', PropertyApiRouter)
app.use('/', OrderApiRouter)
app.use('/', UserInfoApiRouter)
app.use('/', EvaluateApiRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
